let targetWindow = null
let tabCount = 0;
chrome.action.onClicked.addListener((tab) => { 
  chrome.windows.getCurrent(window => { 
    targetWindow = window;

    chrome.tabs.query({ windowId: targetWindow.id }, (tabs) => { 
      // 记录当前窗口tabs的数量
      tabCount = tabs.length;

      // 获取所有chrome窗口
      chrome.windows.getAll({ populate: true }, (windows) => { 
        const numWindows = windows.length;
        let tabPosition = tabCount;

        for (var i = 0; i < numWindows; i++) { 
          let win = windows[i];

          // 如果当前遍历的窗口不是当前目标窗口，则将所有的tab移动到目标窗口
          if(targetWindow.id !== win.id) { 
            let numTabs = win.tabs.length;

            for (let j = 0; j < numTabs; j++) { 
              let tab = win.tabs[j];

              chrome.tabs.move(tab.id, {
                windowId: targetWindow.id,
                index: tabPosition
              })

              tabPosition++;
            }
          }
        }
      })
    })
  })
});